package org.x4444.trans;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * WeekPartition.
 * 
 */
public class WeekPartition {
    private final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    private final Calendar calendar = Calendar.getInstance();


    public WeekPartition() {
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        calendar.setMinimalDaysInFirstWeek(4);
    }

    public String evaluate(String dateString) {
        if (dateString == null) {
            return null;
        }
        try {
            Date date = formatter.parse(dateString);
            calendar.setTime(date);
            
            String partitionName = evalInt();

            return partitionName;
        } catch (ParseException e) {
            return null;
        }
    }

    protected String evalInt() {
        int week = calendar.get(Calendar.WEEK_OF_YEAR);
        int year = calendar.get(Calendar.YEAR);
        
        if (week == 1 || week >= 52) {
            int month = calendar.get(Calendar.MONTH);
            if (month == Calendar.JANUARY && week >= 52) {
                year--;
            } else if (month == Calendar.DECEMBER && week == 1) {
                year++;
            }
        }
        StringBuilder sb = new StringBuilder();
        sb.append(year);
        sb.append("W");
        if (week < 10) {
            sb.append("0");
        }
        sb.append(week);
        return sb.toString();
    }
}
